import React, { Suspense } from 'react';
import { createBrowserRouter, createRoutesFromElements, Navigate, Route, RouterProvider } from 'react-router-dom';
import { useOnUnloadWindow, useScrollbarSize } from 'hooks';
import moment from 'moment';
import smoothscroll from 'smoothscroll-polyfill';
import RootStore from 'store/RootStore';

import Layout from 'components/Layout';
import PrivateRoute from 'components/PrivateRoute';

import 'moment/locale/ru';

moment.locale('en');

const SearchPage = React.lazy(() => import('./pages/SearchPage'));
const RepositoryPage = React.lazy(() => import('./pages/RepositoryPage'));
const UserPage = React.lazy(() => import('./pages/UserPage'));
const BlobPage = React.lazy(() => import('./pages/ContentsPage'));

const App: React.FC = () => {
    useScrollbarSize();
    useOnUnloadWindow();
    smoothscroll.polyfill();
    RootStore.locationStore.setSearch(location.search);

    const router = createBrowserRouter(
        createRoutesFromElements(
            <Route path="/" element={<Layout />}>
                <Route index element={<SearchPage />} />
                <Route
                    path="/user"
                    element={
                        <PrivateRoute>
                            <UserPage />
                        </PrivateRoute>
                    }
                />
                <Route path=":owner/:repository" element={<RepositoryPage />} />
                <Route path=":owner/:repository/contents/*" element={<BlobPage />} />
                <Route path="*" element={<Navigate to="/" />} />
            </Route>,
        ),
    );
    return (
        <Suspense>
            <RouterProvider router={router} />
        </Suspense>
    );
};

export default App;
